// pages/profile/index.ts
const app = getApp()
Page({
  data: {
    nickName: '',
    avatar: '',
  },
  onShow() {
    const app = getApp()
    this.setData({ nickName: app.nickName, avatar: app.avatar })
  },
  getUserNickname(ev) {
    // 更新昵称
    this.updateNickname(ev.detail.value)
  },
  // 更新昵称接口
  async updateNickname(nickName) {
    const app = getApp()
    if (nickName === '') return
    // 调用接口更新用户昵称
    const { code } = await wx.http.put('/userInfo', { nickName })
    // 检测接口是否调用成功
    if (code !== 10000) return wx.utils.toast('更新昵称失败!')
    app.setApp('nickName', nickName)
  },
  changeAvatar(ev) {
    wx.uploadFile({
      filePath: ev.detail.avatarUrl,
      name: 'file',
      url: wx.http.baseURL + '/upload',
      header: {
        Authorization: `Bearer ${app.token}`,
      },
      formData: { type: 'avatar' },
      success: (result) => {
        const data = JSON.parse(result.data)
        if (data.code !== 10000) return wx.utils.toast('上传头像失败!')
        this.setData({ avatar: data.data.url })
        app.setApp('avatar', data.data.url)
      },
    })
  },
})
